﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Collections;
using System.Configuration;

namespace Slja.WEB.WebUI
{
    public partial class SmsMessageSend : System.Web.UI.Page
    {
        SljaSMS.SmsSoapClient _smsclient;
        SljaSMS.SmsSoapClient SmsClient
        {
            get
            {
                if (_smsclient == null)
                {
                   // string url = ConfigurationManager.AppSettings["SljaSmsWebService"];
                   // _smsclient = new SljaSMS.SmsSoapClient("SljaAppEndPointName", url);
                    _smsclient = new SljaSMS.SmsSoapClient("SmsSoap");
                    
                }
                return _smsclient;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            btnSend.Click += new EventHandler(btnSend_Click);
            btnRecive.Click += new EventHandler(btnRecive_Click);
            btnDisconnect.Click += new EventHandler(btnDisconnect_Click);

            AjaxPro.Utility.RegisterTypeForAjax(typeof(SmsMessageSend)); 
        }

        void btnDisconnect_Click(object sender, EventArgs e)
        {

            //if (SmsClient.Disconnect())
            //{ lbStatus.Text = "设备关闭成功！"; }
            //else
            //{
            //    lbStatus.Text = "设备关闭失败！";
            //}
           
        }

        void btnRecive_Click(object sender, EventArgs e)
        {
          
            SljaSMS.ArrayOfSms_MsgRecive arr = null;
            StringBuilder sb = new StringBuilder();
            StringBuilder sbStatus = new StringBuilder();
            bool isOK = true;
            try
            {
                arr = SmsClient.ReciveNewMsg();
            }
            catch (System.ServiceModel.FaultException srvEx)
            {
                if (srvEx.Message.IndexOf("System.UnauthorizedAccessException") > -1)
                {
                    sbStatus.Append("设备端口被占用，无法访问！");                   
                }
                else if (srvEx.Message.IndexOf("System.IO.IOException") > -1)
                {
                    sbStatus.Append("指定的设备端口不存在！");                    
                }
                else
                {
                    sbStatus.Append("短信服务有错误，暂不可用！");
                    pnlMsgHide.InnerText = srvEx.Message;
                }
                isOK = false;
            }
            catch (Exception err)
            {
                sbStatus.Append(err.Message);
                isOK = false;

            }
            if (isOK)
            {
                for (int i = 0; i < arr.Count; i++)
                {
                    sb.Append(arr[i].SendNO + " ");
                    sb.Append(arr[i].MsgContent + " ");
                    sb.Append(arr[i].RecvTime + " ");
                    sb.Append(Environment.NewLine);
                }
                sbStatus.AppendFormat("成功接收{0}条信息。", arr.Count.ToString());
            }
            tbxDownMsg.Text = sb.ToString();
            lbStatus.Text = sbStatus.ToString();
        }

        void btnSend_Click(object sender, EventArgs e)
        {
            string temp = tbxReciver.Text;
            string[] arrTelno = temp.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
            //电话号码
            SljaSMS.ArrayOfString arrRecv = new SljaSMS.ArrayOfString();
            arrRecv.AddRange(arrTelno);
            //电话内容
            string Content = tbxContent.Text.Trim();
           
            //当前用户
            UserSession user = Slja.WEB.SessionBox.GetUserSession();
            //发送
            SljaSMS.ArrayOfSms_MsgSend listResult = SmsClient.Send(arrRecv, Content, user.LoginId);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < listResult.Count; i++)
            {
                sb.Append(listResult[i].ID.ToString() + ",");
            }
            sb.Length--;
            hdfSentMsgIDs.Value = sb.ToString();
           
            //string MsgDescr = ShowResultDescr(listResult, arrTelno, out ErrorTelNO);
            lbStatus.Text = "发送中...";
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showsendstatus", "$(function(){CheckSendStatus();SetRecivingMsg();})", true);
        }
        [AjaxPro.AjaxMethod]
        public SljaSMS.MsgStatus[] GetMsgSendStatus(string IDs)
        {
            SljaSMS.ArrayOfInt arr = new SljaSMS.ArrayOfInt();
            string[] arrIDs = IDs.Split(',');
            for(int i=0;i<arrIDs.Length;i++)
            {
                arr.Add(int.Parse(arrIDs[i]));
            }
            SljaSMS.MsgStatus[] arrSendStatus = SmsClient.GetMsgSendStatus(arr);
            return arrSendStatus;
        }
        [AjaxPro.AjaxMethod]
        public SljaSMS.ArrayOfSms_MsgRecive GetMsgReciving()
        {
            SljaSMS.ArrayOfSms_MsgRecive arr = SmsClient.ReciveNewMsg();
            return arr;
        }
        private string ShowResultDescr(List<uint> listResult, string[] arrTelno, out List<string> SendErrorTelNO)
        {
            //int OKCount = listResult.Count(delegate(int m) { return m == 1; });
            StringBuilder sb = new StringBuilder(); 
            int OKCount = 0;
            SendErrorTelNO = new List<string>();
            for (int i = 0; i < listResult.Count; i++)
            {
                if (listResult[i] == 1)
                {
                    OKCount++;
                }
                else
                {
                    SendErrorTelNO.Add(arrTelno[i]);
                }
            }
            sb.AppendFormat("发送成功{0}条", OKCount.ToString());
            if (SendErrorTelNO.Count > 0)
            {
                sb.AppendFormat(",失败{0}条(", SendErrorTelNO.Count.ToString());
                for (int j = 0; j < SendErrorTelNO.Count; j++)
                {
                    sb.Append(SendErrorTelNO[j] + ",");
                }
                sb.Length--;
                sb.Append(")");
            }
            sb.Append(".");
            return sb.ToString();
        }
    }
}